#pragma once
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;

typedef void (*work_t)(int fd);
typedef void(* task_t)(int fd,pid_t pid);
// 创建任务

// 打印日志
void PrintLog(int fd,pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : printf log task\n" << endl;
}

// 加载任务
void ReloadConf(int fd,pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : ReloadConf task\n" << endl;
}

// 链接数据库
void ConnectMysql(int fd,pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : connect mysql task\n" << endl;
}
// 用户登录
void UserLogin(int fd,pid_t pid)
{
    cout << "sub process: " << pid << ", fd: " << fd<< ", task is : user login task\n" << endl;
}

task_t task_list[4] = {PrintLog, ReloadConf, ConnectMysql, UserLogin};

// 任务列表(worker()函数存放各种任务)
// worker--->CreatProcess(work_t work)--->子进程调用work()函数
// 子进程执行work()函数之前,dup2(pipifd[0],0)<===>fd_array[0]=fd_array[pipefd[0]],因此原先本应从管道中读取任务码,改变为从标准输入中读取任务码即可！
void worker(int fd)
{
    // 子进程从标准输入stdin(stdin->_fileno=0)中读取父进程发送的任务码
    while (true)
    {
        int command_code = 0;
        int n = read(0, &command_code, sizeof(command_code)); // 读取成功,返回实际读取到的字节数
        if (n == sizeof(command_code))
        {
            // 任务码合理性检查
            if (command_code >= 4)
            {
                continue;
            }
            // 执行任务
            task_list[command_code](fd,getpid());
        }
        else if(n==0)
        {
            cout << "sub process: " << getpid() << " quit doing..." << endl;
            break;
        }
    }
}